<template>
  <div class="collection-manage-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>藏品管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="handleRefresh"
        >刷新</el-button>
      </div>
      
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="藏品名称">
          <el-input v-model="queryParams.name" placeholder="请输入藏品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="展览">
          <el-select v-model="queryParams.exhibitionId" placeholder="请选择展览" clearable>
            <el-option
              v-for="item in exhibitionOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格区域 -->
      <el-table
        :data="collectionList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="name" label="藏品名称" align="center"></el-table-column>
        <el-table-column prop="exhibitionName" label="所属展览" align="center"></el-table-column>
        <el-table-column prop="type" label="分类" align="center"></el-table-column>
        <el-table-column prop="era" label="年代" align="center"></el-table-column>
        <el-table-column label="藏品图片" align="center">
          <template slot-scope="scope">
            <el-image 
              style="width: 50px; height: 50px"
              :src="scope.row.image && scope.row.image.startsWith('data:image') ? scope.row.image : 'data:image/jpeg;base64,' + scope.row.image" 
              :preview-src-list="[scope.row.image && scope.row.image.startsWith('data:image') ? scope.row.image : 'data:image/jpeg;base64,' + scope.row.image]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      ></el-pagination>
      
      <!-- 编辑藏品对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="collectionForm" :rules="rules" ref="collectionFormRef" label-width="100px">
          <el-form-item label="藏品名称" prop="name">
            <el-input v-model="collectionForm.name"></el-input>
          </el-form-item>
          <el-form-item label="所属展览" prop="exhibitionId">
            <el-select v-model="collectionForm.exhibitionId" placeholder="请选择展览">
              <el-option
                v-for="item in exhibitionOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分类" prop="type">
            <el-input v-model="collectionForm.type"></el-input>
          </el-form-item>
          <el-form-item label="年代" prop="era">
            <el-input v-model="collectionForm.era"></el-input>
          </el-form-item>
          <el-form-item label="藏品描述" prop="description">
            <el-input type="textarea" v-model="collectionForm.description" rows="4"></el-input>
          </el-form-item>
          <el-form-item label="藏品图片" prop="image">
            <div class="avatar-uploader">
              <div class="el-upload" @click="handleImageClick">
                <img v-if="collectionForm.image" :src="collectionForm.image && collectionForm.image.startsWith('data:image') ? collectionForm.image : 'data:image/jpeg;base64,' + collectionForm.image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
              <input
                type="file"
                ref="fileInput"
                style="display: none"
                accept="image/*"
                @change="handleFileChange"
              >
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'CollectionManage',
  data() {
    return {
      // 查询参数
      queryParams: {
        name: '',
        exhibitionId: '',
        pageNum: 1,
        pageSize: 10
      },
      // 展览选项
      exhibitionOptions: [],
      // 藏品列表
      collectionList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 对话框可见性
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 是否为编辑模式
      editMode: false,
      // 藏品表单
      collectionForm: {
        id: '',
        name: '',
        exhibitionId: '',
        type: '',
        era: '',
        description: '',
        image: ''
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入藏品名称', trigger: 'blur' }
        ],
        exhibitionId: [
          { required: true, message: '请选择所属展览', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请输入分类', trigger: 'blur' }
        ],
        era: [
          { required: true, message: '请输入年代', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入藏品描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取展览选项
    this.getExhibitionOptions()
    // 获取藏品列表
    this.getCollectionList()
    // 如果URL中有exhibitionId参数，则设置查询参数
    if (this.$route.query.exhibitionId) {
      this.queryParams.exhibitionId = Number(this.$route.query.exhibitionId)
      this.handleQuery()
    }
  },
  methods: {
    // 获取展览选项
    async getExhibitionOptions() {
      try {
        const { data: res } = await this.$http.get('/exhibition/all')
        if (res.code === 200) {
          this.exhibitionOptions = res.data
        }
      } catch (error) {
        console.error('获取展览选项失败', error)
        this.$message.error('获取展览选项失败')
      }
    },
    // 获取藏品列表
    async getCollectionList() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get('/collection/list', {
          params: this.queryParams
        })
        if (res.code !== 200) {
          return this.$message.error(res.message || '获取藏品列表失败')
        }
        this.collectionList = res.data.records
        this.total = res.data.total
      } catch (error) {
        console.error('获取藏品列表失败', error)
        this.$message.error('获取藏品列表失败')
      } finally {
        this.loading = false
      }
    },
    // 处理查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getCollectionList()
    },
    // 重置查询
    resetQuery() {
      this.queryParams = {
        name: '',
        exhibitionId: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getCollectionList()
    },
    // 处理刷新
    handleRefresh() {
      this.getCollectionList()
    },
    // 处理页码变化
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum
      this.getCollectionList()
    },
    // 处理每页条数变化
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.queryParams.pageNum = 1
      this.getCollectionList()
    },
    // 处理添加
    handleAdd() {
      this.dialogTitle = '添加藏品'
      this.editMode = false
      this.collectionForm = {
        id: '',
        name: '',
        exhibitionId: this.queryParams.exhibitionId || '',
        type: '',
        era: '',
        description: '',
        image: ''
      }
      this.dialogVisible = true
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑藏品'
      this.editMode = true
      this.collectionForm = { ...row }
      this.dialogVisible = true
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm(`确认删除藏品 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.$http.delete(`/collection/${row.id}`)
          if (res.code !== 200) {
            return this.$message.error(res.message || '删除藏品失败')
          }
          this.$message.success('删除藏品成功')
          this.getCollectionList()
        } catch (error) {
          console.error('删除藏品失败', error)
          this.$message.error('删除藏品失败')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    // 处理图片点击事件
    handleImageClick() {
      this.$refs.fileInput.click()
    },
    // 处理文件选择变化
    handleFileChange(e) {
      const file = e.target.files[0]
      if (!file) return
      
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }
      
      // 将文件转换为base64
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.collectionForm.image = reader.result
        this.$message.success('图片上传成功')
      }
      reader.onerror = () => {
        this.$message.error('图片上传失败')
      }
      
      // 清空文件输入，以便于下次选择同一文件时也能触发change事件
      this.$refs.fileInput.value = ''
    },
    // 提交表单
    submitForm() {
      this.$refs.collectionFormRef.validate(async valid => {
        if (!valid) return
        try {
          let res
          if (this.editMode) {
            // 编辑藏品
            res = await this.$http.put('/collection', this.collectionForm)
          } else {
            // 添加藏品
            res = await this.$http.post('/collection', this.collectionForm)
          }
          if (res.data.code !== 200) {
            return this.$message.error(res.data.message || '操作失败')
          }
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.getCollectionList()
        } catch (error) {
          console.error('操作失败', error)
          this.$message.error('操作失败')
        }
      })
    }
  }
}
</script>

<style scoped>
.collection-manage-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>